package i2.application.checklist.struts.utils;

import i2.application.checklist.entities.Categorie;
import i2.application.checklist.entities.CheckList;
import i2.application.checklist.entities.Livrable;
import i2.application.checklist.entities.Reponse;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Questionnaire {

	private static final Logger logger = LoggerFactory.getLogger(Questionnaire.class);
	
	private List<List<Reponse>> reponseGlobalList;
	
	private ListIterator<Categorie> categorieIterator;
	
	private CheckList checkList;
	
	public Questionnaire() {
	}
	
	public void init(CheckList checkList) {
		this.checkList = checkList;
		List<Categorie> categorieList = new ArrayList<Categorie>();
		for (Livrable livrable : checkList.getLivraison().getLivrables()) {
			// on n'ajoute pas 2 fois la même catégorie
			if (!categorieList.contains(livrable.getCategorie())) {
				categorieList.add(livrable.getCategorie());
			}
		}
		
		categorieIterator = categorieList.listIterator();
		reponseGlobalList = new ArrayList<List<Reponse>>(categorieList.size());
	}
	
	public Categorie nextCategorie() {
		if (categorieIterator.hasNext()) {
			return categorieIterator.next();
		}
		return null;
	}

	public void addReponses(List<Reponse> reponseList) {
		
		for (Reponse reponse : reponseList) {
			checkList.addReponse(reponse);
		}
		
		logger.debug("reponseGlobalList.size() : {}",reponseGlobalList.size());
		logger.debug("categorieIterator.previousIndex() : {}",categorieIterator.previousIndex());
		if (reponseGlobalList.size() <= categorieIterator.previousIndex()) {
			reponseGlobalList.add(reponseList);
		} else {
			reponseGlobalList.set(categorieIterator.previousIndex(), reponseList);
		}
	}

	public List<List<Reponse>> getReponseList() {
		return reponseGlobalList;
	}

	public Categorie goToPreviousQuestions() {
		if (categorieIterator.hasPrevious()) {
			Categorie categorie = categorieIterator.previous();
			if (categorieIterator.hasPrevious()) {
				categorie = categorieIterator.previous();
			}
			return categorie;
		} else {
			logger.debug("categorieIterator n'a pas d'élément précédent");
			return null;
		}
	}

	public CheckList getCheckList() {
		return checkList;
	}
	
}
